package com.huiyujinrong.qiangdanbao.activity.login;


import android.content.Context;

import com.huiyujinrong.qiangdanbao.BorrowHelpApp;
import com.huiyujinrong.qiangdanbao.DaggerModelComponent;
import com.huiyujinrong.qiangdanbao.bean.LoginBean;
import com.huiyujinrong.qiangdanbao.model.LoginModel;
import com.huiyujinrong.qiangdanbao.network.Api;
import com.huiyujinrong.qiangdanbao.utils.SharedHelper;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import javax.inject.Inject;

import happyloan.core.RespEvent;

public class LoginPresenter implements LoginContract.Presenter {

    @Inject
    LoginModel model;
    private LoginContract.View view;
    private Context context;

    public LoginPresenter(LoginContract.View v, Context context) {
        this.view = v;
        this.context = context;
        setupDagger2();
    }

    private void setupDagger2() {
        DaggerModelComponent.builder().appComponent(BorrowHelpApp.get().getAppComponent()).build().inject(this);
    }

    @Override
    public void login(String phone, String password) {
        view.disPlay();
        model.login(phone, password);
    }

    @Override
    public void start() {
        EventBus.getDefault().register(this);
    }

    @Override
    public void end() {
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void respEvent(RespEvent<LoginBean> event) {
        if (event.getUrl().equals(Api.login)) {
            view.disMiss();
            switch (event.getCode()) {
                case RespEvent.Code.SUCCEED:
                    //数据返回成功
                    view.exits();
                    LoginBean loginBean = event.getT();
                    loginBean.getUser_id();
                    SharedHelper.put(context, "user_id", loginBean.getUser_id());
                    SharedHelper.put(context, "balance", loginBean.getBalance());
                    Api.tel = loginBean.getPhone();
                    break;
                case RespEvent.Code.FAILURE:
                    //数据返回错误
                    if (event.isAlert()) {
                        view.showToast(String.valueOf(event.getExtra()));  //提示错误
                    }
                    break;
                case RespEvent.Code.ERROR:
                    //数据返回异常
                    view.showToast("网络不好,稍后再试");
                    break;
            }
        }
    }
}
